package com.example.social.screen

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.ElevatedButton
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.constraintlayout.compose.ConstraintLayout
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavHostController
import coil.compose.AsyncImage
import coil.request.ImageRequest
import com.example.social.R
import com.example.social.item_view.ThreadItemWithImage
import com.example.social.model.UserModel
import com.example.social.navigation.Routes
import com.example.social.screen.component.NotThreadList
import com.example.social.utils.SharedPref
import com.example.social.viewmodel.AuthViewModel
import com.example.social.viewmodel.UserViewModel

@Composable
fun Profile(navController1: NavHostController, navController: NavHostController) {
    val context = LocalContext.current

    val authViewModel: AuthViewModel = viewModel()

    val userViewModel: UserViewModel = viewModel()
    val threads by userViewModel.threads.observeAsState(null)

    val currentUserId = SharedPref.getUid(context)


    val followerList by userViewModel.followerList.observeAsState(emptyList())
    val followingList by userViewModel.followingList.observeAsState(emptyList())

    if (currentUserId.isNotEmpty()) {
        userViewModel.getFollowers(currentUserId)
        userViewModel.getFollowing(currentUserId)
        userViewModel.fetchThreads(currentUserId)
    }

    val user = UserModel(
        nickname = SharedPref.getName(context),
        username = SharedPref.getUserName(context),
        imageurl = SharedPref.getImageUrl(context)
    )
    val imgUrl = SharedPref.getImageUrl(context)

    //参数 true 为立即执行 里面的代码块
    LaunchedEffect(currentUserId) {
        if (currentUserId.isEmpty()) {
            navController.navigate(Routes.Login.routes) {
                popUpTo(Routes.Home.routes) { inclusive = true }
                launchSingleTop = true
            }
        }
    }

    LazyColumn(
        modifier = Modifier.fillMaxSize(),
        contentPadding = PaddingValues(16.dp),
        verticalArrangement = Arrangement.spacedBy(16.dp)
    ) {
        item {
            // ConstraintLayout for Profile Details
            ConstraintLayout(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(16.dp)
            ) {
                val (title, logo, userName, bio, followers, following, button) = createRefs()

                Text(
                    text = "个人详情",
                    style = TextStyle(
                        fontWeight = FontWeight.ExtraBold,
                        fontSize = 24.sp
                    ),
                    modifier = Modifier.constrainAs(title) {
                        top.linkTo(parent.top)
                        start.linkTo(parent.start)
                    }
                )
                AsyncImage(
                    model = ImageRequest.Builder(context)
                        .data(imgUrl)
                        .crossfade(true)
                        .error(R.drawable.undraw_male_avatar)
                        .build(),
                    contentDescription = "Profile Picture",
                    contentScale = ContentScale.Crop,
                    modifier = Modifier
                        .constrainAs(logo) {
                            top.linkTo(title.bottom, margin = 16.dp)
                            start.linkTo(parent.start)
                        }
                        .size(120.dp)
                        .clip(CircleShape),
                )

                Text(
                    text = SharedPref.getName(context),
                    style = TextStyle(fontSize = 20.sp),
                    modifier = Modifier
                        .constrainAs(userName) {
                            top.linkTo(logo.top)
                            start.linkTo(logo.end, margin = 16.dp)
                        }
                        .padding(top = 10.dp)
                )

                Text(
                    text = SharedPref.getBio(context),
                    style = TextStyle(fontSize = 16.sp),
                    modifier = Modifier
                        .constrainAs(bio) {
                            top.linkTo(userName.bottom, margin = 8.dp)
                            start.linkTo(logo.end, margin = 16.dp)
                        }
                        .padding(top = 10.dp)
                )
                Text(
                    text = "关注数: ${followerList.size ?: 0}",
                    style = TextStyle(fontSize = 16.sp),
                    modifier = Modifier.constrainAs(followers) {
                        top.linkTo(logo.bottom, margin = 16.dp)
                        start.linkTo(parent.start)
                    }
                )
                Text(
                    text = "正在关注: ${followingList.size ?: 0}",
                    style = TextStyle(fontSize = 16.sp),
                    modifier = Modifier.constrainAs(following) {
                        top.linkTo(followers.bottom, margin = 8.dp)
                        start.linkTo(parent.start)
                    }
                )

                ElevatedButton(
                    onClick = {
                        authViewModel.logout(context) {
                            navController.navigate(Routes.Login.routes) {
                                popUpTo(Routes.Home.routes) { inclusive = true }
                                launchSingleTop = true
                            }
                        }
                    },
                    modifier = Modifier.constrainAs(button) {
                        top.linkTo(following.bottom, margin = 16.dp)
                        start.linkTo(parent.start)
                    }
                ) {
                    Text(text = "登出")
                }
            }
            //代替已经废弃的Divider()
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(1.dp)
                    .background(Color.LightGray) // 自定义颜色
            )
            Text(
                text = "我发布的话题", style = TextStyle(
                    fontSize = 18.sp,
                    fontWeight = FontWeight.Bold
                ), modifier = Modifier.padding(start = 20.dp,top=10.dp)
            )
        }

        if (threads.isNullOrEmpty()) {
            item {
                NotThreadList("用户暂未发布文章")
            }
        } else {
                // 遍历数据并根据不同条件渲染不同布局
                items(threads!!) { thread ->
                    // 如果线程内容很长，显示包含图片的布局
                    ThreadItemWithImage(
                        thread = thread,
                        users = user,
                        navHostController = navController,
                    )
                }
            }
        }
    }
